/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;

import com.koron.purpose.bean.SafetyActivityLedgerBean;
import com.koron.purpose.bean.SafetyActivityPersonBean;
import com.koron.purpose.mapper.SafetyActivityMapper;
import com.koron.purpose.service.api.SafetyActivityService;
import com.koron.purpose.utils.BusinessCode;
import com.koron.purpose.utils.PdfFileUtil;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;


import java.util.*;


@Service
public class SafetyActivityServiceImpl implements SafetyActivityService {
    private final Logger logger = LoggerFactory.getLogger(SafetyActivityServiceImpl.class);

    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;
    
    @Autowired
    private PdfFileUtil pdfFileUtil;

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<DataBean<Map>> querySafetyActivityLedgers(String wcorpCode, String activityType, String corpName,
                                                                 String departmentName, String startTime, String stopTime,
                                                                 Integer page, Integer pageSize) {
        MessageBean<DataBean<Map>> msg = new MessageBean<>();
        SessionFactory factory = new SessionFactory();
        try {
            SafetyActivityMapper mapper = factory.getMapper(SafetyActivityMapper.class);
            Map<String, Object> map = new HashMap<>();
            map.put("wcorpCode", wcorpCode);
            map.put("activityType", activityType);
            map.put("corpName", corpName);
            map.put("departmentName", departmentName);
            if (!"null".equals(startTime)) {
                map.put("startTime", startTime);
            }
            if (!"null".equals(stopTime)) {
                map.put("stopTime", stopTime);
            }
            // 分页起始位置
            Integer pageStart = (page - 1) * pageSize;
            map.put("pageStart", pageStart);
            map.put("pageStop", pageSize);
            // 条件查询
            List list = mapper.querySafActivityLeds(map);
            DataBean dataBean = new DataBean();
            dataBean.setList(list);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            // 总条数
            Integer totalNumber = mapper.countSafActivityLeds(map);
            int num = totalNumber / pageSize;
            // 总页数
            Integer totalPage = totalNumber % pageSize == 0 ? num : num + 1;
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询活动台账列表成功");
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @SuppressWarnings("deprecation")
    @Override
    public List<Map> querySafetyActivityLedgers(String wcorpCode, String activityType, String corpName, String departmentName, String startTime, String stopTime) {
        MessageBean<DataBean<Map>> msg = new MessageBean<>();
        List list = null;
        try (SessionFactory factory = new SessionFactory();) {
            SafetyActivityMapper mapper = factory.getMapper(SafetyActivityMapper.class);
            Map<String, Object> map = new HashMap<>();
            map.put("wcorpCode", wcorpCode);
            map.put("activityType", activityType);
            map.put("corpName", corpName);
            map.put("departmentName", departmentName);
            map.put("startTime", startTime);
            map.put("stopTime", stopTime);
            // 条件查询
            list = mapper.querySafActivityLeds(map);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return list;
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<Map> queryById(String id) {
        MessageBean<Map> msg = MessageBean.create(0, "success", Map.class);
        try (SessionFactory factory = new SessionFactory()) {
            SafetyActivityMapper mapper = factory.getMapper(SafetyActivityMapper.class);
            SafetyActivityLedgerBean bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("该安全活动台账已经不存在");
            } else {
                Map map = bean.toMap();
                // 查询 安全活动人员
                List<Map> persons = mapper.queryPersonBySALId(id);
                map.put("personBeans", JSON.toJSONString(persons));
                msg.setData(map);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
        }
        return msg;
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> insertSafetyActLedg(SafetyActivityLedgerBean bean, StaffBean user,
                                              List<SafetyActivityPersonBean> personBeans, MultipartFile[] files) {
        MessageBean<?> msg = MessageBean.create(0, "success", void.class);
        if (StringUtils.isEmpty(bean.getActivityName()) || StringUtils.isEmpty(bean.getActivityType())
                || StringUtils.isEmpty(bean.getActivityPrincipal()) || StringUtils.isEmpty(bean.getActivityPrincipalName())
                || StringUtils.isEmpty(bean.getCorpCode()) || StringUtils.isEmpty(bean.getCorpName())
                || StringUtils.isEmpty(bean.getDepartmentCode()) || StringUtils.isEmpty(bean.getDepartmentName())
                || bean.getStartTime() == null || bean.getStopTime() == null) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        if (bean.getStopTime().getTime() < bean.getStartTime().getTime()) {
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription("开始时间不能晚于结束时间");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            // 新增 附件
            String fileMsgs = saveFiles(files);
            SafetyActivityMapper mapper = factory.getMapper(SafetyActivityMapper.class);
            // 新增 安全活动台账表
            bean.setActivityAccessory(fileMsgs);
            Date date = new Date();
            bean.setAddTime(date);
            bean.setAddUser(user.getCode());
            bean.setAddUserName(user.getName());
            bean.setUpdateTime(date);
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            String id = DefaultIdGenerator.getInstance().generateLongId();
            bean.setId(id);
            mapper.insertSafetyActLedger(bean);
            if (personBeans != null && personBeans.size() > 0) {
                // 参数组装和校验
                for (SafetyActivityPersonBean personBean : personBeans) {
                    if (StringUtils.isEmpty(personBean.getPersonCode()) || StringUtils.isEmpty(personBean.getPersonName())) {
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("添加活动人员不能为空");
                        return msg;
                    }
                    if (StringUtils.isEmpty(personBean.getDeparCode()) || StringUtils.isEmpty(personBean.getDeparName())) {
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("添加活动人员部门不能为空");
                        return msg;
                    }
                    if (StringUtils.isEmpty(personBean.getCorpCode()) || StringUtils.isEmpty(personBean.getCorpName())) {
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("公司不能为空");
                        return msg;
                    }
                    if (personBean.getAwardedMarks() == null) {
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("加分不能为空");
                        return msg;
                    }
                    personBean.setId(DefaultIdGenerator.getInstance().generateLongId());
                    personBean.setSafetyAActivityLedgerId(id);
                }
                // 新增 安全活动人员表
                // savePersons(personBeans, id, mapper);
                mapper.insertSafetyActPerson(personBeans);
            }
            // 关闭
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
        }finally {
            factory.close();
        }
        return msg;
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> deleteSafetyActivity(String id) {
        MessageBean<?> msg = MessageBean.create(0, "success", void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            SafetyActivityMapper mapper = factory.getMapper(SafetyActivityMapper.class);
            // 根据id查询 安全活动台账
            SafetyActivityLedgerBean bean = mapper.queryById(id);
            if (bean == null) {
                factory.close(false);
                msg.setCode(35001);
                msg.setDescription("数据库连接异常");
                return msg;
            }
            // 删除 安全活动台账
            mapper.deleteSafetyActivityLedger(id);
            // 删除 安全活动人员
            mapper.deleteSafetyActivityPerson(id);
            // 删除附件
            String accessoryStr = bean.getActivityAccessory();
            if (!StringUtils.isEmpty(accessoryStr)) {
                JSONArray array = JSON.parseArray(accessoryStr);
                Iterator iterator = array.iterator();
                JSONObject jsonObject;
                while (iterator.hasNext()) {
                    jsonObject = (JSONObject) iterator.next();
                    Optional.ofNullable(jsonObject.get("fileUrl")).ifPresent(u -> {
                        if (!StringUtils.isEmpty(u.toString())){
                            fastDFSClientWrapper.deleteFile(u.toString());
                        }
                    });
                    Optional.ofNullable(jsonObject.get("pdfUrl")).ifPresent(u -> {
                        if (!StringUtils.isEmpty(u.toString())){
                            fastDFSClientWrapper.deleteFile(u.toString());
                        }
                    });
                }
            }
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
        }
        return msg;
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean updateSafetyActivity(StaffBean user, SafetyActivityLedgerBean bean, String activityAccessory,
                                            List<SafetyActivityPersonBean> personBeans, MultipartFile[] files) {
        MessageBean msg = MessageBean.create(0, "success", void.class);
        if (StringUtils.isEmpty(bean.getActivityName()) || StringUtils.isEmpty(bean.getActivityType())
                || StringUtils.isEmpty(bean.getActivityPrincipal()) || StringUtils.isEmpty(bean.getActivityPrincipalName())
                || StringUtils.isEmpty(bean.getCorpCode()) || StringUtils.isEmpty(bean.getCorpName())
                || StringUtils.isEmpty(bean.getDepartmentCode()) || StringUtils.isEmpty(bean.getDepartmentName())
                || bean.getStartTime() == null || bean.getStopTime() == null) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            SafetyActivityMapper mapper = factory.getMapper(SafetyActivityMapper.class);
            // 根据id 查询 安全会议
            SafetyActivityLedgerBean ledgerBean = mapper.queryById(bean.getId());
            if (ledgerBean == null) {
                msg.setCode(35002);
                msg.setDescription("参数校验异常");
                factory.close(false);
                return msg;
            }
            List<Map> deleteFileUrls = new LinkedList<>();
            // 删除会议记录文件
            String accessory = ledgerBean.getActivityAccessory();
            if (!StringUtils.isEmpty(accessory)) {
                List<Map> accessorys_old = JSON.parseArray(accessory, Map.class);
                List<Map> accessorys_new;
                if (!StringUtils.isEmpty(activityAccessory)) {
                    accessorys_new = JSON.parseArray(activityAccessory, Map.class);
                    for (Map map : accessorys_old) {
                        if (!filter(map, accessorys_new, "fileUrl")) {// 不存在:删除文件
                            deleteFileUrls.add(map);
                        }
                    }
                }
            }
            String activityAccessoryStr = "";
            // 附件保存
            if (files != null) {
                JSONArray array;
                if (!StringUtils.isEmpty(activityAccessory)) {
                    array = JSON.parseArray(activityAccessory);
                } else {
                    array = new JSONArray();
                }
                JSONObject object;
                for (MultipartFile file : files) {
                    object = new JSONObject();
                    object.put("filename", file.getOriginalFilename());
                    object.put("fileUrl", fastDFSClientWrapper.uploadFile(file));
                    object.put("pdfUrl", pdfFileUtil.getPdfUrl(file, fastDFSClientWrapper));
                    array.add(object);
                }
                activityAccessoryStr = JSON.toJSONString(array);
            }
            bean.setActivityAccessory(activityAccessoryStr);
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            // 修改 安全活动台账 信息
            int i = mapper.updateSafetyActLedger(bean);
            // 参数校验
            if (personBeans != null && personBeans.size() > 0) {
                for (SafetyActivityPersonBean personBean : personBeans) {
                    if (StringUtils.isEmpty(personBean.getPersonCode()) || StringUtils.isEmpty(personBean.getPersonName())) {
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("添加活动人员不能为空");
                        return msg;
                    }
                    if (StringUtils.isEmpty(personBean.getDeparCode()) || StringUtils.isEmpty(personBean.getDeparName())) {
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("添加活动人员部门不能为空");
                        return msg;
                    }
                    if (StringUtils.isEmpty(personBean.getCorpCode()) || StringUtils.isEmpty(personBean.getCorpName())) {
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("公司不能为空");
                        return msg;
                    }
                    if (personBean.getAwardedMarks() == null) {
                        msg.setCode(BusinessCode.EXCEPTION.getCode());
                        msg.setDescription("加分不能为空");
                        return msg;
                    }
                }
            }
            // 修改 安全活动人员 信息
            updatePersons(personBeans, bean.getId(), mapper);
            factory.close();
            // 删除文件服务器上的文件
            if (deleteFileUrls != null && deleteFileUrls.size() > 0) {
                for (Map url : deleteFileUrls) {
                    Optional.ofNullable(url.get("fileUrl")).ifPresent(u -> {
                        if (!StringUtils.isEmpty(u.toString())){
                            fastDFSClientWrapper.deleteFile(u.toString());
                        }
                    });
                    Optional.ofNullable(url.get("pdfUrl")).ifPresent(u -> {
                        if (!StringUtils.isEmpty(u.toString())){
                            fastDFSClientWrapper.deleteFile(u.toString());
                        }
                    });
                }
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
        }finally {
            factory.close();
        }
        return msg;
    }

    /**
     * 判断map中的 key是否在list中存在
     *
     * @param map
     * @param list
     * @param key
     * @return
     */
    private boolean filter(Map<String, String> map, List<Map> list, String key) {
        String str = map.get(key);
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        if (list == null || list.size() == 0) {
            return false;
        }
        for (Map m : list) {
            if (str.equals(Optional.ofNullable(m.get(key)).get().toString())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 保存附件
     *
     * @param files
     * @return 返回附件信息json数据格式
     */
    private String saveFiles(MultipartFile[] files) throws Exception {
        if (files == null || files.length == 0) {
            return null;
        }
        JSONArray array = new JSONArray();
        JSONObject object;
        for (MultipartFile file : files) {
            object = new JSONObject();
            object.put("filename", file.getOriginalFilename());
            object.put("fileUrl", fastDFSClientWrapper.uploadFile(file));
            object.put("pdfUrl", pdfFileUtil.getPdfUrl(file, fastDFSClientWrapper));
            array.add(object);
        }
        return JSON.toJSONString(array);
    }

    /**
     * 保存 安全活动人员表
     *
     * @param personBeans
     * @param safetyActivityLedgerId 安全活动台账id
     */
    private void savePersons(List<SafetyActivityPersonBean> personBeans, String safetyActivityLedgerId, SafetyActivityMapper mapper) throws Exception {
        for (SafetyActivityPersonBean personBean : personBeans) {
            personBean.setId(DefaultIdGenerator.getInstance().generateLongId());
            personBean.setSafetyAActivityLedgerId(safetyActivityLedgerId);
        }
        mapper.insertSafetyActPerson(personBeans);
    }

    /**
     * 修改 安全活动人员表
     *
     * @param personBeans            安全活动人员信息
     * @param safetyActivityLedgerId 安全活动台账id
     */
    private void updatePersons(List<SafetyActivityPersonBean> personBeans, String safetyActivityLedgerId,
                               SafetyActivityMapper mapper) throws Exception {
        // 删除 安全活动人员记录
        mapper.deleteSafetyActivityPerson(safetyActivityLedgerId);
        if (personBeans != null && personBeans.size() > 0) {
            for (SafetyActivityPersonBean personBean : personBeans) {
                personBean.setId(DefaultIdGenerator.getInstance().generateLongId());
                personBean.setSafetyAActivityLedgerId(safetyActivityLedgerId);
            }
            mapper.insertSafetyActPerson(personBeans);
        }
    }
}
